<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <div class="title">更换头像</div>
      </div>
    </template>
    <ImgUpload :image="user.avatar" @onImageChange="onImageChange" />
    <div class="submit">
      <el-form-item>
        <el-button @click="router.back()">返回</el-button>
        <el-button type="primary" @click="saveHandle"> 保存 </el-button>
      </el-form-item>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { putAdminAvatarAPI } from '@/api/admin/admin'
import { putBusinessAvatarAPI } from '@/api/business/business'
import ImgUpload from '@/components/ImgUpload/index.vue'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const userStore = useUserStore()
const user = ref(userStore.user)
const onImageChange = (value: string) => {
  user.value.avatar = value
}
// 保存
const saveHandle = async () => {
  const id = user.value.id
  const avatar = user.value.avatar
  if (avatar) {
    try {
      if (userStore.rule === 'admin') {
        await putAdminAvatarAPI(id, avatar)
      } else {
        await putBusinessAvatarAPI(id, avatar)
      }
      ElMessage.success('修改成功')
      router.back()
    } catch (error) {
      console.log(error)
    }
  } else {
    ElMessage.error('请上传头像')
  }
}
</script>
<style scoped lang="scss">
.submit {
  margin-top: 20px;
}
</style>
